package com.bestv.bsr.core.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * http sign
 * <p>
 * Created by admin on 2017/12/22.
 */
public class SignUtils {

    private static final String SIGN_PARAM_NAME = "_sign";
    private static final String TIME_PARAM_NAME = "_time";

    public static void sign(Map<String, String> params, String signKey) {
        if (params == null || StringUtils.isAnyBlank(signKey)) {
            return;
        }
        long time = System.currentTimeMillis();
        params.put(TIME_PARAM_NAME, Long.toString(time));
        StringBuilder sb = buildParamStr(params);
        sb.append(signKey);
        String sign = DigestUtils.md5Hex(sb.toString());
        params.put(SIGN_PARAM_NAME, sign);
    }

    public static boolean check(HttpServletRequest request, String signKey) {
        if (request == null || StringUtils.isAnyBlank(signKey)) {
            return false;
        }
        String signParam = request.getParameter(SIGN_PARAM_NAME);
        if (StringUtils.isAnyBlank(signParam)) {
            return false;
        }
        Map<String, String> params = new HashMap<>();
        Enumeration<String> paramNameEnum = request.getParameterNames();
        while (paramNameEnum.hasMoreElements()) {
            String paramName = paramNameEnum.nextElement();
            if (StringUtils.equals(paramName, SIGN_PARAM_NAME)) {
                continue;
            }
            params.put(paramName, request.getParameter(paramName));
        }
        StringBuilder sb = buildParamStr(params);
        sb.append(signKey);
        String sign = DigestUtils.md5Hex(sb.toString());
        return StringUtils.equals(signParam, sign);
    }

    public static StringBuilder buildParamStr(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        if (!params.isEmpty()) {
            List<String> paramNames = new ArrayList<>(params.keySet());
            Collections.sort(paramNames);
            for (String paramName : paramNames) {
                if (sb.length() > 0) {
                    sb.append("&");
                }
                sb.append(paramName).append("=").append(params.get(paramName));
            }
        }
        return sb;
    }
}
